//
//  FunctionTabBarController.m
//  TaduNewUI
//
//  Created by Xu Deheng on 12-5-21.
//  Copyright (c) 2012年 ___MyCompony__ All rights reserved.
//

#import "XTabBarController.h"

#if TARGET_OS_IPHONE

#import "TabBarView.h"
#import "ButtonsGroup.h"
#import "UIDevice+Ext.h"
#import "FunctionSet.h"

@interface XTabBarController ()

- (void)_customizedTabBarView:(UIView*)baseView;
- (void)_onClick_tabBarItem:(id)sender;
- (void)_addSubViewController:(UIViewController *) viewController;
- (void)_deleteSubViewController:(UIViewController *) viewController;
- (void)_resizeContentView;
- (void)_resizeTabBarView;
@end


@implementation XTabBarController

@synthesize tabBarView = _tabBarView;
@synthesize delegate = _delegate;
@synthesize viewControllers = _viewControllers;
@synthesize contentView = _contentView;
@synthesize currentViewController = _currentViewController;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        _viewControllersLock = [[NSLock alloc] init];
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#if !ARC_ENABLED
- (void)dealloc
{
    [_tabBarView release];
    [_viewControllers release];
    [_contentView release];
    [_currentViewController release];
    [_viewControllersLock release];
    _delegate = nil;
    [super dealloc];
}
#endif

#pragma mark - View lifecycle

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView
{
}
*/


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
    CGRect frame;
    
    self.view.frame = [UIScreen mainScreen].applicationFrame;
    
    [self _customizedTabBarView:self.view];

    if (nil == _contentView) {
        frame = self.view.frame;
        _contentView = [[UIView alloc] init];
        frame.origin = CGPointZero;
        frame.size.width = self.view.bounds.size.width;
        frame.size.height = self.view.bounds.size.height - self.tabBarView.frame.size.height;
        _contentView.frame = frame;
        [self.view addSubview:_contentView];
    }
}


- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    self.view = nil;
    self.tabBarView = nil;
    
    if ([[[UIDevice currentDevice] systemVersion] floatValue] < 5.0) {
        [self.currentViewController viewDidUnload];
    }
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    if (osVersion() < 5.0) {
        [self.currentViewController viewWillAppear:animated];
    }
    
    self.view.backgroundColor = [UIColor scrollViewTexturedBackgroundColor];
    
    //resize contentView
    [self resizeContentView];
        
    //resize tabbar
    _tabBarFrame.origin.y = self.contentView.frame.origin.y + self.contentView.frame.size.height;
    
    CGRect frame = self.tabBarView.frame;
    frame.origin.y = self.contentView.frame.origin.y + self.contentView.frame.size.height;
    self.tabBarView.frame = frame;
    
    //config tabbar button item title
    int count = self.tabBarView.items.count;
    for (int i = 0; i < count; i++) {
        UIButton *btn = [self.tabBarView.items objectAtIndex:i];
        [btn setTitle:[[self.viewControllers objectAtIndex:i] title] forState:UIControlStateNormal];
    }    
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    if (osVersion() < 5.0) {
        [self.currentViewController viewDidAppear:animated];
    }
    

    NSLog(@"%s contentView :%@  view :%@", __func__, NSStringFromCGRect(self.contentView.frame), NSStringFromCGRect(self.view.frame));
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    if (osVersion() < 5.0) {
        [self.currentViewController viewWillDisappear:animated];
    }
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    if (osVersion() < 5.0) {
        [self.currentViewController viewDidDisappear:animated];
    }
}

- (void)setTabBarView:(TabBarView *)tabBarView
{
    XRetain(tabBarView);
    XRelease(_tabBarView);
    _tabBarView = tabBarView;
    
    //add on to view
    CGRect frame = _tabBarView.frame;
    frame.origin.x = 0;
    frame.origin.y = self.view.frame.size.height - frame.size.height;
    [self.view addSubview:_tabBarView];
    _tabBarFrame = _tabBarView.frame;
}

- (void)resizeContentView
{
    CGRect frame = _contentView.frame;
    frame.origin = CGPointZero;
    frame.size.height = self.view.frame.size.height - _tabBarView.frame.size.height;
    frame.size.width = self.view.frame.size.width;
    _contentView.frame = frame;
}

- (CGFloat)tabBarItemWidthAtIndex:(NSUInteger)atIndex
{
    return (_tabBarView.bounds.size.width) / _viewControllers.count;
}

//标签的最大数量
const int _item_max_count = 100;

- (NSData*)xTabBarItemCoordinates
{
    NSMutableData *data = [NSMutableData dataWithCapacity:_item_max_count];
    float locats[_item_max_count];
    assert(_viewControllers.count <= _item_max_count);
    float __totals = 0.;
    for (int i = 0; i < _viewControllers.count; i++) {
        float unit_width = [self tabBarItemWidthAtIndex:i];
        float half_unit_width = unit_width / 2.0f;
        locats[i] = half_unit_width + __totals;
        __totals += unit_width;
    }
    [data appendBytes:locats length:_item_max_count];
    return data;
}

#pragma mark - hidden method
- (void)_customizedTabBarView:(UIView *)baseView
{
    if (nil == _tabBarView) {
        CGRect frame;
        // config tabbar background
        frame.size.width = baseView.bounds.size.width;
        frame.size.height = kTABBAR_DEFAULT_HEIGHT;
        frame.origin = CGPointMake(0, baseView.bounds.size.height - frame.size.height);
        
        _tabBarView = [[TabBarView alloc] init];
        _tabBarView.delegate = self;
        _tabBarView.frame = frame;
        _tabBarView.backgroundColor = [UIColor orangeColor];
        _tabBarFrame = _tabBarView.frame;
        
        // config tab bar view and tab bar customized items
        float *locats = (float*)[self xTabBarItemCoordinates].bytes;
        
        int count = _viewControllers.count;
        NSMutableArray *tmp = [NSMutableArray arrayWithCapacity:4];
        
        [self.tabBarView.buttonsGroup removeAllButtons];
        
        for (int i = 0; i < count; i++) {
            float unit_width = [self tabBarItemWidthAtIndex:i];
            frame.size = CGSizeMake(unit_width, _tabBarView.bounds.size.height);
            GroupButton *btn = [[GroupButton alloc] initWithFrame:frame];
            [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            [btn setTitleColor:[UIColor blackColor] forState:UIControlStateHighlighted];
            btn.center = CGPointMake(locats[i], _tabBarView.bounds.size.height / 2.0);
            [btn addTarget:self action:@selector(_onClick_tabBarItem:) forControlEvents:UIControlEventTouchUpInside];
            
            [_tabBarView.buttonsGroup addGroupButton:btn];
            [_tabBarView addSubview:btn];
            
            //[btn setBackgroundImage:[UIImage imageWithColor:[UIColor clearColor] imageSize:btn.bounds.size] forState:UIControlStateNormal];
            //[btn setBackgroundImage:[UIImage imageWithColor:[UIColor clearColor] imageSize:btn.bounds.size] forState:UIControlStateHighlighted];
            
            btn.titleLabel.font = [UIFont systemFontOfSize:13.0];
            [tmp addObject:btn];
            XRelease(btn);
        }
        
        self.tabBarView.items = tmp;
        [baseView addSubview:_tabBarView];    
    }
}

- (void)_resizeContentView
{
    CGRect frame = self.contentView.frame;
    frame.origin.y = 0;
    frame.size.height = self.contentView.superview.frame.size.height - _tabBarFrame.size.height;
    self.contentView.frame = frame;
}

- (void)_resizeTabBarView
{
    _tabBarFrame.origin.y = self.contentView.frame.origin.y + self.contentView.frame.size.height;
    _tabBarFrame.size.height = kTABBAR_DEFAULT_HEIGHT;
}

- (void)_onClick_tabBarItem:(id)sender
{
    if ([sender isKindOfClass:[UIButton class]]) {
        _selectedIndex = [self.tabBarView.items indexOfObject:sender];
        if (_selectedIndex == NSNotFound) {
            return;
        }
        
        UIViewController *vc = [_viewControllers objectAtIndex:_selectedIndex];
        //recall the delegate protocol method
        if (![vc isEqual:self.currentViewController]) {
            if ([[[UIDevice currentDevice] systemVersion] floatValue] < 5.0) {
                [vc viewWillAppear:YES];
            }
        }
        
        if (_delegate && [_delegate respondsToSelector:@selector(tabBarController:shouldSelectViewController:)]) {
            if (![_delegate tabBarController:self shouldSelectViewController:vc]) {
                return;
            }
        }
        
        if (_delegate && [_delegate respondsToSelector:@selector(tabBarController:willSelectingViewController:)]) {
            [_delegate tabBarController:self willSelectingViewController:vc];
        }
        
        //present the selected view controller 
        if (![vc isEqual:self.currentViewController]) {
            CGRect frame;
            frame = vc.view.frame;
            frame.origin = CGPointZero;
            frame.size.width = self.view.bounds.size.width;
            frame.size.height = self.view.bounds.size.height - _tabBarView.bounds.size.height - self.navigationController.navigationBar.frame.size.height;
            vc.view.frame = frame;
            
            [_contentView addSubview:vc.view];//add new view
            [self.currentViewController.view removeFromSuperview];//remove old view
            self.currentViewController = vc;//hold new view controller
            if (osVersion() < 5.0) {
                [vc viewDidAppear:YES];
            }
            [self _deleteSubViewController:_currentViewController];
            [self _addSubViewController:vc];
        }
        //NSLog(@"%s  view :%@ currrentView :%@  contentView :%@", __func__, NSStringFromCGRect(self.view.frame), NSStringFromCGRect(self.currentViewController.view.frame), NSStringFromCGRect(self.contentView.frame));
        
        //NSLog(@"view999  %@, selected :%u", [vc.view viewWithTag:999], _selectedIndex);
        //recall the delegate protocol method
        if (_delegate && [_delegate respondsToSelector:@selector(tabBarController:didSelectViewController:)]) {
            [_delegate tabBarController:self didSelectViewController:vc];
        }
        
    }
}

- (void)_addSubViewController:(UIViewController *)viewController
{
    if (osVersion() >= 5.0) {
        [self addChildViewController:viewController];
    }
}

- (void)_deleteSubViewController:(UIViewController *)viewController
{
    if (osVersion() >= 5.0) {
        [viewController removeFromParentViewController];
    }
}
#pragma mark - tab bar overidden methods

- (void)setViewControllers:(NSArray *)viewControllers
{
    [_viewControllersLock lock];
    //reset the selected index
    _selectedIndex = 0;
    //hold the viewcontrolelrs
    XRetain(viewControllers);
    
    XRelease(_viewControllers);
    //may be need remove view in view controllers
    //.............
    _viewControllers = viewControllers;
    
    //update bar item title
    if (self.tabBarView) {
        int count = _viewControllers.count;
        for (int i = 0; i < count; i++) {
            GroupButton *barItem = [self.tabBarView.items objectAtIndex:i];
            UIViewController *vc = [_viewControllers objectAtIndex:i];
            [barItem setTitle:vc.title forState:UIControlStateNormal];
        }
    }
    
    CGRect frame;
    UIViewController *vc = [_viewControllers objectAtIndex:_selectedIndex];
    if (_currentViewController != vc) {
        if (self.view) {
            frame = vc.view.frame;
            frame.origin = CGPointZero;
            frame.size.width = _contentView.bounds.size.width;
            frame.size.height = _contentView.bounds.size.height;
            vc.view.frame = frame;
            vc.view.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
            [_contentView addSubview:vc.view];
        }
        
        [self _deleteSubViewController:_currentViewController];
        [self _addSubViewController:vc];
    
        //remove previous view.
        [self.currentViewController.view removeFromSuperview];
        //reassign new view controlelr.
        self.currentViewController = vc;
    }
    
    [_viewControllersLock unlock];
    
//    if (_delegate && [_delegate respondsToSelector:@selector(tabBarController:didSelectViewController:)]) {
//        [_delegate tabBarController:self didSelectViewController:vc];
//    }

}

- (void)setTabBarHidden:(BOOL)isHidden animated:(BOOL)animated
{
    __block CGRect frame = self.tabBarView.frame;
    [UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionAllowUserInteraction animations:^{
        if (isHidden) {
            frame.origin.y = self.view.frame.size.height;
            frame.size.height = 0;
            _tabBarView.frame = frame;
        }else {
            _tabBarView.frame = _tabBarFrame;
        }
    } completion:^(BOOL finished) {
        if (!isHidden) {
            frame = _contentView.frame;
            frame.size.height = self.view.frame.size.height - _tabBarView.frame.size.height;
            _contentView.frame = frame;
        }
    }];
    
    if (isHidden) {
        frame = _contentView.frame;
        frame.size.height = self.view.frame.size.height - _tabBarView.frame.size.height;
        _contentView.frame = frame;
    }else {
        self.tabBarView.frame = _tabBarFrame;
    }
    //NSLog(@"%s;  hidden :%u; animation :%u; %@;\n%@", __FUNCTION__, isHidden, animated, NSStringFromCGRect(self.tabBarView.frame), NSStringFromCGRect(_tabBarFrame));

}


@end

#endif
